package com.sqx.modules.errand.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sqx.common.utils.PageUtils;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.dao.UserDao;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.entity.UserMoneyDetails;
import com.sqx.modules.app.service.UserMoneyDetailsService;
import com.sqx.modules.errand.dao.ErrandComplaintDao;
import com.sqx.modules.errand.dao.ErrandIllegalTypeDao;
import com.sqx.modules.errand.dao.ShopIllegalTypeDao;
import com.sqx.modules.errand.dao.TbIndentDao;
import com.sqx.modules.errand.entity.ErrandComplaint;
import com.sqx.modules.errand.entity.ErrandIllegalType;
import com.sqx.modules.errand.entity.ShopIllegalType;
import com.sqx.modules.errand.entity.TbIndent;
import com.sqx.modules.errand.service.ErrandComplaintService;
import com.sqx.modules.order.entity.TbOrder;
import com.sqx.modules.order.service.AppOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class ErrandComplaintServiceImpl extends ServiceImpl<ErrandComplaintDao, ErrandComplaint> implements ErrandComplaintService {

    @Autowired
    private ErrandComplaintDao errandComplaintDao;
    @Autowired
    private ErrandIllegalTypeDao errandIllegalTypeDao;
    @Autowired
    private ShopIllegalTypeDao shopIllegalTypeDao;
    @Autowired
    private TbIndentDao tbIndentDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private UserMoneyDetailsService userMoneyDetailsService;
    @Autowired
    private AppOrderService appOrderService;

    @Transactional
    @Override
    public Result insertComplaint(ErrandComplaint errandComplaint) {
        //根据投诉类型查扣款金额
        Long illegalId = errandComplaint.getIllegalId();
        Long shopIllegalId = errandComplaint.getShopIllegalId();

        BigDecimal forfeitMoney = null;
        //添加投诉记录
        TbIndent indent = tbIndentDao.selectIndentByIndentNumber(errandComplaint.getIndentNumber());
        if(errandComplaint.getType()==1){
            ErrandIllegalType illegalType = errandIllegalTypeDao.selectById(illegalId);
            forfeitMoney = illegalType.getForfeitMoney();
            errandComplaint.setIndentType(indent.getIndentType());
            errandComplaint.setRiderUserId(indent.getRiderUserId());
        }else {
            TbOrder tbOrder = appOrderService.selectOrderByNum(errandComplaint.getIndentNumber());
            TbIndent tbIndent = tbIndentDao.selectOne(new QueryWrapper<TbIndent>().eq("order_id", tbOrder.getOrderId()));
            ShopIllegalType shopIllegalType = shopIllegalTypeDao.selectById(shopIllegalId);
            forfeitMoney = shopIllegalType.getForfeitMoney();
            errandComplaint.setIndentType(tbIndent.getIndentType());
            errandComplaint.setRiderUserId(tbIndent.getRiderUserId());
        }
        errandComplaint.setDeductMoney(forfeitMoney);
        errandComplaint.setComplaintTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        errandComplaint.setComplaintState(5);
        baseMapper.insert(errandComplaint);
        return Result.success();
    }

    @Override
    public Result findAllComplaint(Long userId, Integer illegalId, Integer complaintState, Integer page, Integer limit) {
        Page<ErrandComplaint> pages=new Page<>(page,limit);
        PageUtils pageUtils = new PageUtils(baseMapper.findAppComplaint(pages, userId, illegalId, complaintState));
        return Result.success().put("data", pageUtils);
    }

    @Override
    public Result findComplaint(Long userId, Long complaintId) {
        ErrandComplaint errandComplaint = baseMapper.findComplaint(complaintId);
        return Result.success().put("data", errandComplaint);
    }

    @Override
    public Result appealIndent(Long userId, ErrandComplaint errandComplaint) {
        errandComplaint.setComplaintState(2);
        errandComplaint.setAppealTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        baseMapper.updateById(errandComplaint);
        return Result.success();
    }

    @Override
    public Result findAllAppeal(Integer page, Integer limit, Long userId, Integer illegalId, Integer complaintState, String indentNumber) {
        Page<ErrandComplaint> pages=new Page<>(page,limit);
        PageUtils pageUtils = new PageUtils(baseMapper.findAllComplaint(pages,userId, illegalId, complaintState, indentNumber));
        return Result.success().put("data", pageUtils);
    }

    @Transactional
    @Override
    public Result updateCustomerComplaint(Long complaintId, Integer complaintState) {
        if(complaintState==1){
            //投诉通过，状态改为1
            ErrandComplaint errandComplaint = new ErrandComplaint();
            errandComplaint.setComplaintId(complaintId);
            errandComplaint.setComplaintState(1);
            baseMapper.updateById(errandComplaint);
            //扣保证金
            ErrandComplaint errandComplaint1 = baseMapper.selectById(complaintId);
            UserEntity userEntity1 = userDao.selectById(errandComplaint1.getRiderUserId());
            BigDecimal subtract;

            if(errandComplaint1.getDeductMoney().doubleValue()>userEntity1.getCashDeposit().doubleValue()){
                //如果保证金不够，则保证金改为0
                subtract = BigDecimal.valueOf(0);
            }else {
                //如果保证金足够，则扣除保证金
                subtract = userEntity1.getCashDeposit().subtract(errandComplaint1.getDeductMoney());
            }
            UserEntity userEntity = new UserEntity();
            userEntity.setUserId(errandComplaint1.getRiderUserId());
            userEntity.setCashDeposit(subtract);
            userDao.updateById(userEntity);
            //退保证金的记录
            UserMoneyDetails userMoneyDetails=new UserMoneyDetails();
            userMoneyDetails.setUserId(errandComplaint1.getRiderUserId());
            userMoneyDetails.setTitle("扣除保证金");
            userMoneyDetails.setContent("被投诉订单，扣除保证金："+errandComplaint1.getDeductMoney()+"元！");
            userMoneyDetails.setType(2);
            userMoneyDetails.setClassify(1);
            userMoneyDetails.setMoney(errandComplaint1.getDeductMoney());
            userMoneyDetails.setCreateTime(new SimpleDateFormat("yyyy-MM-dd :HH:mm:ss").format(new Date()));
            userMoneyDetailsService.save(userMoneyDetails);

        }else {
            //投诉未通过，修改投诉状态为6
            ErrandComplaint sysComplaint = new ErrandComplaint();
            sysComplaint.setComplaintId(complaintId);
            sysComplaint.setComplaintState(6);
            baseMapper.updateById(sysComplaint);
        }
        return Result.success();
    }

    @Transactional
    @Override
    public Result updateComplaintState(ErrandComplaint errandComplaint) {
        baseMapper.updateById(errandComplaint);
        //如果申诉通过，则将罚金退回骑手余额
        if(errandComplaint.getComplaintState()==4){
            Long complaintId = errandComplaint.getComplaintId();
            ErrandComplaint sysComplaint1 = baseMapper.selectById(complaintId);
            UserEntity userEntity = userDao.selectById(sysComplaint1.getRiderUserId());
            BigDecimal subtract = userEntity.getCashDeposit().subtract(sysComplaint1.getDeductMoney());
            UserEntity userEntity1 = new UserEntity();
            userEntity1.setCashDeposit(subtract);
            userDao.updateById(userEntity1);
            //添加一条退款记录到钱包表
            UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
            userMoneyDetails.setUserId(sysComplaint1.getRiderUserId());
            userMoneyDetails.setTitle("申诉成功");
            userMoneyDetails.setContent("退还保证金：" + sysComplaint1.getDeductMoney());
            userMoneyDetails.setType(1);
            userMoneyDetails.setState(2);
            userMoneyDetails.setMoney(sysComplaint1.getDeductMoney());
            userMoneyDetails.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            userMoneyDetailsService.save(userMoneyDetails);
        }
        return Result.success();
    }

    @Override
    public Result selectComplaint(Long userId, Integer page, Integer limit) {
        Page<ErrandComplaint> pages = new Page<>(page, limit);
        IPage<ErrandComplaint> errandComplaintIPage = errandComplaintDao.selectUserComplaint(pages, userId);
        PageUtils pageUtils = new PageUtils(errandComplaintIPage);
        return Result.success().put("data", pageUtils);
    }
}
